#!/usr/bin/python

import Backfire

import re
import cgi
import cgitb

print "Content-type: text/html\n"

cgitb.enable()
params = cgi.FieldStorage()

def readEntireFile(filename):
    """ Read all of <filename> and return as a string """
    try:
        text_file = open(filename, "r")
        whole_thing = text_file.read()
        text_file.close()
    except IOError as (errno, stderror):
        return ""
    
    return whole_thing

def writeAllText(filename, contents):
    """ Overwrite <filename> with the string, <contents> """
    text_file = open(filename, "w")
    text_file.write(contents)
    text_file.close()


def filepathFromUri(uri):
    """ Transforms a uri into a filepath on the server.
    This function is specific to your server set up."""
    
    filenameMatch = re.search(r"/(\w*\.css)$", uri)
    if (filenameMatch == None):
        return None

    filename = "Css/" + filenameMatch.group(1)
    return filename


def LoadCssFromFile(uri):
    """ Callback given to Backfire to load your CSS files"""

    Backfire.log("LoadCssFromFile: " + uri)

    filename = filepathFromUri(uri)
    Backfire.log("filepath: " + filename);

    contents = readEntireFile(filename)
    return contents

def SaveCssToFile(uri, contents):
    """ Callback given to Backfire to save your CSS files"""

    Backfire.log("SaveCssToFile: "+uri)
    Backfire.log("contents: " + contents)

    filename = filepathFromUri(uri)
    Backfire.log("filepath: " + filename);

    writeAllText(filename, contents)
    return True

def VerifyAccessOnLoad():
    Backfire.send_message_to_client(Backfire.ACCESS_GRANTED)

def ProcessChanges():
    changes = params['backfire-changes'].value
    result = Backfire.process(changes, LoadCssFromFile, SaveCssToFile)
    Backfire.send_message_to_client(result)

# Begin Script Execution
if ("cmd" not in params):
    # In this case, it is a get request which happens on the initial load
    VerifyAccessOnLoad()
elif (params["cmd"].value == "process"):
    # Otherwise, the save changes button has been pressed.  So process and save.
    ProcessChanges()
